package com.zhuangfei.hpuhelper.tools;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import com.hpu.bean.RoomBean;
import com.zhuangfei.hpuhelper.bean.PhoneBean;

import android.content.Context;

/**
 * 电话黄页工具类
 * 加载数据，查询数据
 * @author Administrator
 *
 */
public class PhoneTools {
	
	@SuppressWarnings("unused")
	private static List<PhoneBean> phoneBeans=new ArrayList<>();
	
	/**
	 * 静态方法，用于从文本中加载电话数据，存入集合中
	 * @return
	 */
	public static List<PhoneBean> loadPhone(Context context,String file){
		List<PhoneBean> phoneBeans = new ArrayList<>();
		try {
			InputStreamReader is=new InputStreamReader(context.getAssets().open(file), "UTF-8");
			BufferedReader reader = new BufferedReader(is);
			String lineTxt = null;
			while ((lineTxt = reader.readLine()) != null) {
				if(lineTxt.indexOf(";")!=-1) {
					String[] arr = lineTxt.split(";");
					phoneBeans.add(new PhoneBean(arr[0], arr[1], arr[2]));
				}
				else phoneBeans.add(new PhoneBean(lineTxt, null,null));
				
			}
			reader.close();
			is.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		PhoneTools.phoneBeans=phoneBeans;
		return phoneBeans;
	}
	
	/**
	 * 静态方法
	 * @return
	 */
	public static List<RoomBean> loadInstitude(Context context,String file){
		List<RoomBean> list = new ArrayList<>();
		try {
			InputStreamReader is=new InputStreamReader(context.getAssets().open(file), "UTF-8");
			BufferedReader reader = new BufferedReader(is);
			String lineTxt = null;
			while ((lineTxt = reader.readLine()) != null) {
				if(lineTxt.charAt(0)!=';'){
					String[] arr=lineTxt.split(";");
					list.add(new RoomBean(arr[0],arr[1]));
				}
				
			}
			reader.close();
			is.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}
	
	
	/**
	 * 根据三个要素进行模糊搜索
	 * @param key 关键字
	 * @return 搜索到的数据集合 
	 */
	public static List<PhoneBean> searchByKey(List<PhoneBean> phoneBeans,String key){
		List<PhoneBean> results=new ArrayList<>();
		for(PhoneBean bean:phoneBeans){
			if(bean.getDepartment().indexOf(key)!=-1||bean.getOffice().indexOf(key)!=-1||bean.getPhone().indexOf(key)!=-1){
				results.add(bean);
			}
		}
		return results;
	}
}
